package handlers

import (
	"encoding/json"
	"gin-blog/catche"
	"gin-blog/models"
	"gin-blog/pkg"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"time"
)

// 登录缓存UsersLogin
func UsersLogin(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "用户名或者密码不能为空",
		})
		return
	}
	//redis判断密码是否错误3次
	redis_login_key := "redis_login_key" + username
	errcount, _ := catche.Rdb.Get(catche.Ctx, redis_login_key).Int()
	if errcount > 3 {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "密码错误3次",
		})
		return
	}
	//mysql判断用户是否存在
	var user models.User
	err := models.DB.Where("username = ?", username).First(&user).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	//判断密码是否正确
	if user.Password != pkg.Md5Str(password) {
		catche.Rdb.Incr(catche.Ctx, redis_login_key)
		if errcount == 2 {
			catche.Rdb.Set(catche.Ctx, redis_login_key, 3, time.Hour*2)

			c.JSON(http.StatusOK, gin.H{
				"code": 500,
				"msg":  "密码错误3次,封禁2个小时",
			})
			return
		}
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "登录成功",
	})

}
func UsersList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	//从缓存查询数据
	var users []models.User
	redis_list_page_key := "redis_list_page_key" + strconv.Itoa(page)
	catcheJson, _ := catche.Rdb.Get(catche.Ctx, redis_list_page_key).Result()
	if catcheJson == "" {
		models.DB.Offset(offset).Limit(size).Find(&users)
		jsonData, _ := json.Marshal(&users)
		catche.Rdb.Set(catche.Ctx, redis_list_page_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(catcheJson), &users)

	}
	var count int64
	models.DB.Model(&models.User{}).Count(&count)
	c.JSON(http.StatusOK, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  users,
		"count": count,
	})
	return
}
func UsersDetail(c *gin.Context) {
	id := c.Query("id")
	var users models.User
	redis_del_key := "redis_del_key" + id
	catcheJson, _ := catche.Rdb.Get(catche.Ctx, redis_del_key).Result()
	if catcheJson == "" {
		models.DB.Where("id  = ?", id).First(&users)
		jsonData, _ := json.Marshal(users)
		catche.Rdb.Set(catche.Ctx, redis_del_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(catcheJson), &users)
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "详情查询成功",
		"data": users,
	})
	return
}
